<?php
/*
 * Created on Apr 11, 2009
 * @ fileName: /library/common.php
 *  
 */
	/**
	 * @abstract This function take an image and create different copies of different sizes for it
	 * @param $structure : 
	 * 		"ustore"
	 * @param $dirName: original image's directory
	 * 		e.g: /var/www/hvn/public/ustore/1/images/original/gallery/
	 * @param $fileName: file name only
	 * 		e.g: spring.jpg
	 * @param $wmDir
	 * 		/var/www/hvn/public/watermark
	 * @param $configSizes: array of different sizes 
	 * 		e.g: array("xsmall", "small", "medium", ..)
	 *  
	 * @param $configSizes: array of different sizes in Pixels 
	 * 		e.g: array(50, 100, 200, ..)
	 * @param $userId: UserId who uploaded
	 * @param $createWM: Whether or not to create a watermarked version of each resized image
	 * 
	 * @return: true or false (success or not)
	 * 
	 */ 
    function generate_image_copies($structureType, $dirName, $fileName, $wmDir, $configSizes = null, $configSizesInPixel = null, $userId, $createWm)
 	{
 		/*
 		 * for structureType = "ustore" (just a code name)
 		 * $dirName = /var/www/hvn/public/ustore/1/images/original/gallery/
 		 * 
 		 * We need to get
 		 * 		$resizedDirName =  /var/www/hvn/public/ustore/1/images/%s/gallery/
 		 * 		to be able to save to different resized images, such as
 		 * 							/var/www/hvn/public/ustore/1/images/MEDIUM/gallery/
 		 *
 		 * 		$resizedWmDirName =  /var/www/hvn/public/UFILES/1/images/%s/gallery/
 		 * 
 		 */
 		if ($structureType == 'ustore')
 		{
 			//TODO: check pattern
 			$pattern = "/\/public\/ustore\/(\d+)\/([^\/]*)\/original\/(.*)/";
			$resizedReplace = '/public/ustore/${1}/${2}/%s/${3}';
        	$resizedDirName = preg_replace($pattern, $resizedReplace, $dirName);
        	
			$resizedWmReplace = '/public/ufiles/${1}/${2}/%s/${3}';
           	$resizedWmDirName = preg_replace($pattern, $resizedWmReplace, $dirName);
           	//die ($resizedWmDirName);
 		} 	

		//get size of image source:
		if (is_null($configSizes))
		{
			//get from configuration
			$configSizes = explode(",", Zend_Registry::get('configuration')->imageresize->configSizes);
			$configSizesInPixel = explode(",",Zend_Registry::get('configuration')->imageresize->configSizesInPixel);
			/*
			$configSizes = array("xxsmall","xsmall", "small", "medium", "large", "xlarge");
			$configSizesInPixel = array("30", "75", "100", "260", "350", "600", "1300");
			*/
			
		}
		
        require_once "Utils/Image.php";
//        $img = new Utils_Image("/var/www/clucms/public/abc/asas/asdf/asf/asdf/asdf/asdf/asdf/asdf/asdf/asdf/asdf/1.jpeg");
        //die($img->width);
//        die($dirName.$fileName);
 		$imageObj = new Utils_Image($dirName.$fileName);
// 		$imageObj = new Utils_Image("/var/www/clucms/public/abc/asas/asdf/asf/asdf/asdf/asdf/asdf/asdf/asdf/asdf/asdf/1.jpeg");
		$imageWidth = $imageObj->width;
		if (!isset($imageWidth) || $imageWidth == 0)
			return false;
		$imageHeight = $imageObj->height;
		$size = max($imageWidth, $imageHeight);
		
		//First, create a Wm image of the original picture
		/*
		if($createWm === true)
		{
			$resizedWmOriginalDir = sprintf($resizedWmDirName, "original");
			if(!file_exists($resizedWmOriginalDir))
				mkdir($resizedWmOriginalDir, 0777  , true);
			create_wm($imageObj, $resizedWmOriginalDir, $fileName, $wmDir, $imageWidth, $imageHeight,10,10);
		}
		*/
		$resizedWmOriginalDir = sprintf($resizedWmDirName, "original");
		if(!file_exists($resizedWmOriginalDir))
			mkdir($resizedWmOriginalDir, 0777  , true);
		if($createWm === true) 
			create_wm($imageObj, $resizedWmOriginalDir, $fileName, $wmDir, $imageWidth, $imageHeight,10,10);
		else //e.g no need to wm avatar, just copy it over
			copy ($dirName.$fileName, $resizedWmOriginalDir. $fileName ); 
			
			
		$count = count ($configSizes);
		if ($configSizesInPixel[$count - 1] <= $size)
			$k = $count -1 ;
		else
		{
    		$k = 0;
    		for($i = 0; $i <= count($configSizes) - 1; $i++)
    		{
    			if( $size >= $configSizesInPixel[$i] && $size <= $configSizesInPixel[$i+1])
    			{
    				$k = $i;
    				break;
    			}
    		}
		}			
			
		for($j = 0; $j <= $k; $j++)
		{
			$resizedDir = sprintf($resizedDirName, $configSizes[$j]);//APP_PATH."/public/ustore/$userId/images/$configSizes[$j]/gallery/";
			if (!file_exists($resizedDir))
				mkdir($resizedDir, 0777  , true);
			$imageObj->create_resize($resizedDir.$fileName, null, $configSizesInPixel[$j], $configSizesInPixel[$j]);
			
			//create Wm dir
			$resizedWmDir = sprintf($resizedWmDirName, $configSizes[$j]);
			if(!file_exists($resizedWmDir))
				mkdir($resizedWmDir, 0777  , true);
			//only watermark for big enough images
			if (($configSizes[$j] == "medium" || $configSizes[$j] == "large" || $configSizes[$j] == "xlarge") && $createWm)
			{
				create_wm($imageObj, $resizedWmDir, $fileName, $wmDir, $configSizesInPixel[$j], $configSizesInPixel[$j],10,10);
			}
			else //create resized only
			{
				$imageObj->create_resize($resizedWmDir.$fileName, null, $configSizesInPixel[$j], $configSizesInPixel[$j]);
			}
		}
		
		return true;
	}
 
 	// create file watermask
    function create_wm($imageObj, $resizedWmDir, $fileName, $wmDir, $w, $h, $x = 0, $y = 0)
	{
		$config = array('0','100','200','300', '400', '500','600', '700_plus');
		$width = "700_plus";
		for($i = 0; $i< count($config) - 1; $i++)
		{
			if($config[$i] <= $w && $w <= $config[$i+1])
				$width = $config[$i] . "_" . $config[$i+1];
		}
		
		$height = "700_plus";
		for($j = 0; $j< count($config) - 1; $j++)
		{
			if(($config[$j]) <= $h && $h <= ($config[$j+1]))
				$height = $config[$j]."_".$config[$j+1];
		}
		
		$size = $width.'_'.$height;
		
		$watermarkfile = $wmDir.'hvn'.$size.'.png';
		/*
		if(max($w, $h) > 700)
		{
			$watermarkfile =  $wmDir.'hvn600_700_plus_600_700_plus.png';
		}
		*/
		
		$wmFileName = $imageObj->create_resize($resizedWmDir.$fileName, $watermarkfile, $w, $h, $x, $y);
		if($wmFileName)
			return $wmFileName;
		else 
			return false;
	}

	
	// Do a cleanup of the folder name to avoid possible problems
	function SanitizeFolderName( $sNewFolderName )
	{
        $sNewFolderName = stripslashes( $sNewFolderName ) ;

        // Remove . \ / | : ? * " < >
        $sNewFolderName = preg_replace( '/\\.|\\\\|\\/|\\||\\:|\\?|\\*|"|<|>|[[:cntrl:]]/', '_', $sNewFolderName ) ;

        return $sNewFolderName ;
	}

	// Do a cleanup of the file name to avoid possible problems
	function SanitizeFileName( $sNewFileName )
	{
        global $Config ;
        $sNewFileName = stripslashes( $sNewFileName ) ;

        // Replace dots in the name with underscores (only one dot can be there... security issue).
        //if ( $Config['ForceSingleExtension'] )
                $sNewFileName = preg_replace( '/\\.(?![^.]*$)/', '_', $sNewFileName ) ;
        // Remove \ / | : ? * " < >
        $sNewFileName = preg_replace( '/\\\\|\\/|\\||\\:|\\?|\\*|"|<|>|[[:cntrl:]]/', '_', $sNewFileName ) ;
        return $sNewFileName ;
	}	
	
	/*
	 * With an image url like "/public/ufiles/42/images/small/gallery/1/Photo0097.jpg"
	 * remove all the copies in 
	 */
	function remove_image_copies($fileName)
	{
	}
	
 	
	function get_key($key){
		$db = Zend_Db_Table::getDefaultAdapter();
		$sql = "SELECT p.value FROM  config_variables  p WHERE p.key = '$key'";
		$ret = $db->fetchRow($sql);
		if($ret['value'])
			return $ret['value'];
		else
			return null;
 	}
 	
 	function get_rid($uid){
		$db = Zend_Db_Table::getDefaultAdapter();
		$sql = "SELECT u.rid FROM  user_roles u WHERE u.uid = '$uid'";
		$ret = $db->fetchRow($sql);
		if($ret['rid'])
			return $ret['rid'];
		else
			return null;
 	}
 	
 	
 	function set_user_activities($user_id,$action,$content,$target,$target_id){
		$db = Zend_Db_Table::getDefaultAdapter();
		try{
			$sql = "INSERT user_activities VALUES('".$user_id."','".$action."','".$content."','".$target."','".$target_id."','".time()."')";
			$db->query($sql);
			return true;
		} catch(Exception $e){
			die($e->getMessase());
			return false;
		}
 	}
 	
	 	
	function __($str)
	{
	    return $str;
	    //return Zend_Registry::get('Zend_Translate')->_($str);
	}
	
	function clu_array_merge($keys, $arr)
	{
		$ret = array();
		foreach ($keys as $k)
			$ret[$k] = isset($arr[$k]) ? $arr[$k] : null;
		return $ret;
	}
	
	//convert string time to integer
	function string_to_date($dateStr)
	{
		if (empty($dateStr))
			return null;
		$countArray = count(split('[/.-]', $dateStr));
		if($countArray > 2)
		{
			list($day, $month, $year ) = split('[/.-]', $dateStr);
			$tmp = (int)$year*500 + (int)$month*35 + (int)$day;
		}
		else
		{
			$value = split('[/.-]', $dateStr);
			if($countArray == 2 && strlen($value['1']) == 4)
			{
				list($month, $year ) = split('[/.-]', $dateStr);
				$tmp = (int)$year*500 + (int)$month*35;
			}
			else
			{
				list($day, $month) = split('[/.-]', $dateStr);
				$tmp = (int)$month*35 + (int)$day;
			}
		}
	//	list($day, $month, $year ) = split('[/.-]', $dateStr);
	//	$tmp = (int)$year*500 + (int)$month*35 + (int)$day;
		return $tmp; 
	}
	
	function date_to_string($dateInt)
	{
		if (empty($dateInt))
			return null;
		$tmp = array(($dateInt%500)%35,intval(($dateInt%500)/35),intval($dateInt/500));
		return join("/",$tmp);
	}
	
	function str_first_words($string, $wordsreturned)
	{
	  	$retval = $string;    
	  	$array = explode(" ", $string);
		if (count($array) < $wordsreturned)
	  		$retval = $string;
		else
		{
	  		array_splice($array, $wordsreturned);
	  		$retval = implode(" ", $array)." ...";
		}
	  	return $retval;
	}
	
	function get_language_index($lang)
	{
		$arr = array ("vi" => 0,
					  "en" => 1,
					  "cn" => 2, "jp" => 3
		)	;
		return $arr[$lang];
	}
	
	function get_language_from_int($index)
	{
		$arr = array ( 0 => "vi",
					  1 => "en",
					  2 => "cn",
					  3 => "jp"
		)	;
		return $arr[$index];
	}
	
	function get_status_from_int($index)
	{
		$arr = array(
				   0 => 'published',
				   1 => 'featured',  
				   2 => 'queued', 
				   3 => 'unpublished',
				   4 => 'deleted'
	    );
		return $arr[$index];
	}
	
	/*
	 * TODO: rename keyword "type" to avoid NodeType & category type here
	 */
	function encode_search_url($searchData, $nodeType, $contentType = null)
	{
		$ret = "";
		if(!$contentType) //node
			$ret = $ret . "&type=$nodeType";
		
		foreach ($searchData as $key=>$val)
		{
			
			if ($key == "type" && $contentType == "place" && isset($searchData['type']))
			{
				if(!is_array($searchData['type']))
					$ret = $ret . "&type=" . $searchData['type'];
				else
					$ret = $ret . "&type=" . implode(",", $searchData['type']);
			}
			// leave out the 'page' param because this will be concatenated with
			// the page number in paginationControl
			else if (($key != "page") && ($key != "success") && ($key != "errorMessage") && ($key != "type"))
			{
				$ret = $ret ."&$key=$val";
			}
		}
		$ret = $ret . "&cluSearch=1";
		if (isset($_REQUEST['searchAll']))
		$ret = $ret . "&searchAll=1";
		return $ret;
		
	}
		
	function substring_n_words($string, $numberWords)
	{ 
		$returnString = "";
		$words = explode(" ",$string);
		$count=0;
		foreach($words as $word)
		{
			if(!empty($word))
			{
				$returnString =   $returnString .  $word ." ";
				$count++;  
			}
			if($count == $numberWords)
			{
				break;            
			}
		} 
		return $returnString;  
	}

	// return the English day of the week by number 
	// 2 = Monday, 3 = Tuesday...
	function weekday_from_num($num)
	{
		$days = array (
			2 => Monday,
			3 => Tuesday,
			4 => Wednesday,
			5 => Thursday,
			6 => Friday,
			7 => Saturday,
			8 => Sunday,
		);
		return $days[$number];
	}
	
	function dump($a)
	{
		echo "<pre>";
	    print_r($a);
	    echo "</pre>";
	
	}
	function die_a ($a)
	{
		echo "<pre>";
	    print_r($a);
	    echo "</pre>";
	    die();
	}
function VN_unaccent($item)
{
  static $search, $replace;
  $trans=array(               'á'=>'a','à'=>'a','ả'=>'a','ã'=>'a','ạ'=>'a', 
                    'ă'=>'a', 'ắ'=>'a','ằ'=>'a','ẳ'=>'a','ẵ'=>'a','ặ'=>'a',         
                    'â'=>'a', 'ấ'=>'a','ầ'=>'a','ẩ'=>'a','ẫ'=>'a','ậ'=>'a',         
                              'Á'=>'A','À'=>'A','Ả'=>'A','Ã'=>'A','Ạ'=>'A', 
                    'Ă'=>'A', 'Ắ'=>'A','Ằ'=>'A','Ẳ'=>'A','Ẵ'=>'A','Ặ'=>'A',         
                    'Â'=>'A', 'Ấ'=>'A','Ầ'=>'A','Ẩ'=>'A','Ẫ'=>'A','Ậ'=>'A',
                              'đ'=>'d','Đ'=>'D',
                              'é'=>'e','è'=>'e','ẻ'=>'e','ẽ'=>'e','ẹ'=>'e',
                    'ê'=>'e', 'ế'=>'e','ề'=>'e','ể'=>'e','ễ'=>'e','ệ'=>'e',
                              'É'=>'E','È'=>'E','Ẻ'=>'E','Ẽ'=>'E','Ẹ'=>'E', 
                    'Ê'=>'E', 'Ế'=>'E','Ề'=>'E','Ể'=>'E','Ễ'=>'E','Ệ'=>'E',
                              'í'=>'i','ì'=>'i','ỉ'=>'i','ĩ'=>'i','ị'=>'i', 
                              'Í'=>'I','ì'=>'i','Ỉ'=>'I','ĩ'=>'i','ị'=>'i', 
                              'ó'=>'o','ò'=>'o','ỏ'=>'o','õ'=>'o','ọ'=>'o', 
                    'ô'=>'o', 'ố'=>'o','ồ'=>'o','ổ'=>'o','ỗ'=>'o','ộ'=>'o',         
                    'ơ'=>'o', 'ớ'=>'o','ờ'=>'o','ở'=>'o','ỡ'=>'o','ợ'=>'o',         
                              'Ó'=>'O','Ò'=>'O','Ỏ'=>'O','Õ'=>'O','Ọ'=>'O', 
                    'Ô'=>'O', 'Ố'=>'O','Ồ'=>'O','Ổ'=>'O','Ỗ'=>'O','Ộ'=>'O', 
                    'Ơ'=>'O', 'Ớ'=>'O','Ờ'=>'O','Ở'=>'O','Ỡ'=>'O','Ợ'=>'O',         
                              'ú'=>'u','ù'=>'u','ủ'=>'u','ũ'=>'u','ụ'=>'u', 
                    'ư'=>'u', 'ứ'=>'u','ừ'=>'u','ử'=>'u','ữ'=>'u','ự'=>'u', 
                              'Ú'=>'U','Ù'=>'U','Ủ'=>'U','Ũ'=>'U','Ụ'=>'U', 
                    'Ư'=>'U', 'Ứ'=>'U','Ừ'=>'U','Ử'=>'U','Ữ'=>'U','Ự'=>'U', 
                              'ý'=>'y','ỳ'=>'y','ỷ'=>'y','ỹ'=>'y','ỵ'=>'y', 
                              'Ý'=>'Y','Ỳ'=>'Y','Ỷ'=>'Y','Ỹ'=>'Y','Ỵ'=>'Y' );
  if (!$search)
  {
    $search = $replace = array(); // Get the HTML entities table into an array
    //$trans = get_html_translation_table(HTML_ENTITIES); // Go through the entity mappings one-by-one
    //print_r($trans);
    foreach ($trans as $literal => $entity)
    { // Make sure we dont process any other characters // such as fractions, quotes etc:
      if (ord($literal) >= 192)
      { // Get the accented form of the letter
        $search[] = $literal; // Get e.g. E from the string ɒ $replace[] = $entity1;
        $replace[]= $entity;
      }
    }
  }
  return str_replace($search, $replace, $item);
}



function VN_unaccent_vowels($item)
{
  static $search, $replace;
  $trans=array(               'á'=>'a','à'=>'a','ả'=>'a','ã'=>'a','ạ'=>'a', 
                    'ă'=>'a', 'ắ'=>'a','ằ'=>'a','ẳ'=>'a','ẵ'=>'a','ặ'=>'a',         
                    'â'=>'a', 'ấ'=>'a','ầ'=>'a','ẩ'=>'a','ẫ'=>'a','ậ'=>'a',         
                              'Á'=>'A','À'=>'A','Ả'=>'A','Ã'=>'A','Ạ'=>'A', 
                    'Ă'=>'A', 'Ắ'=>'A','Ằ'=>'A','Ẳ'=>'A','Ẵ'=>'A','Ặ'=>'A',         
                    'Â'=>'A', 'Ấ'=>'A','Ầ'=>'A','Ẩ'=>'A','Ẫ'=>'A','Ậ'=>'A',
                              'é'=>'e','è'=>'e','ẻ'=>'e','ẽ'=>'e','ẹ'=>'e',
                    'ê'=>'e', 'ế'=>'e','ề'=>'e','ể'=>'e','ễ'=>'e','ệ'=>'e',
                              'É'=>'E','È'=>'E','Ẻ'=>'E','Ẽ'=>'E','Ẹ'=>'E', 
                    'Ê'=>'E', 'Ế'=>'E','Ề'=>'E','Ể'=>'E','Ễ'=>'E','Ệ'=>'E',
                              'í'=>'i','ì'=>'i','ỉ'=>'i','ĩ'=>'i','ị'=>'i', 
                              'Í'=>'I','ì'=>'I','Ỉ'=>'I','ĩ'=>'I','ị'=>'I', 
                              'ó'=>'o','ò'=>'o','ỏ'=>'o','õ'=>'o','ọ'=>'o', 
                    'ô'=>'o', 'ố'=>'o','ồ'=>'o','ổ'=>'o','ỗ'=>'o','ộ'=>'o',         
                    'ơ'=>'o', 'ớ'=>'o','ờ'=>'o','ở'=>'o','ỡ'=>'o','ợ'=>'o',         
                              'Ó'=>'O','Ò'=>'O','Ỏ'=>'O','Õ'=>'O','Ọ'=>'O', 
                    'Ô'=>'O', 'Ố'=>'O','Ồ'=>'O','Ổ'=>'O','Ỗ'=>'O','Ộ'=>'O', 
                    'Ơ'=>'O', 'Ớ'=>'O','Ờ'=>'O','Ở'=>'O','Ỡ'=>'O','Ợ'=>'O',         
                              'ú'=>'u','ù'=>'u','ủ'=>'u','ũ'=>'u','ụ'=>'u', 
                    'ư'=>'u', 'ứ'=>'u','ừ'=>'u','ử'=>'u','ữ'=>'u','ự'=>'u', 
                              'Ú'=>'U','Ù'=>'U','Ủ'=>'U','Ũ'=>'U','Ụ'=>'U', 
                    'Ư'=>'U', 'Ứ'=>'U','Ừ'=>'U','Ử'=>'U','Ữ'=>'U','Ự'=>'U', 
                              'ý'=>'y','ỳ'=>'y','ỷ'=>'y','ỹ'=>'y','ỵ'=>'y', 
                              'Ý'=>'Y','Ỳ'=>'Y','Ỷ'=>'Y','Ỹ'=>'Y','Ỵ'=>'Y' );
  if (!$search)
  {
    $search = $replace = array(); // Get the HTML entities table into an array
    //$trans = get_html_translation_table(HTML_ENTITIES); // Go through the entity mappings one-by-one
    //print_r($trans);
    foreach ($trans as $literal => $entity)
    { // Make sure we dont process any other characters // such as fractions, quotes etc:
      if (ord($literal) >= 192)
      { // Get the accented form of the letter
        $search[] = $literal; // Get e.g. E from the string ɒ $replace[] = $entity1;
        $replace[]= $entity;
      }
    }
  }
  return str_replace($search, $replace, $item);
}


function archin_menu_get_index($name)
{
	$menuTabs = array ("home", "people", "project", "post", "gallery", "account", "api");
	$tmp =  array_keys($menuTabs, $name);
	return $tmp[0];
}
function archin_category_name_from_index($idx)
{
	$categories = array (0, "kien_truc", "qui_hoach", "noi_that", "thi_cong");
	return $categories[$idx];
}
?>
